﻿using EShop.Net.Configuration;
using EShop.Net.Loging;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace EShop.Net.Core.SqlSugar
{
    /// <summary>
    /// SqlSugar启动服务
    /// </summary>
    public static class SqlSugarSetup
    {
        public static void AddSqlSugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            //注入 ORM
            SugarIocServices.AddSqlSugar(new IocConfig()
            {
                //数据库连接
                ConnectionString = AppSettingsConstVars.DbSqlConnection,
                //判断数据库类型
                DbType = AppSettingsConstVars.DbDbType == IocDbType.MySql.ToString() ? IocDbType.MySql : IocDbType.SqlServer,
                //是否开启自动关闭数据库连接
                IsAutoCloseConnection = true,
            });

            //设置参数
            services.ConfigurationSugar(db =>
            {
                db.CurrentConnectionConfig.InitKeyType = InitKeyType.Attribute;

                #region 创建数据库CodeFirst模式【更改数据库结构时放开】
                //var basePath = AppContext.BaseDirectory;
                //var servicesDllFile = Path.Combine(basePath, "EShop.Net.Model.dll");  // 反射获取程序集
                //Assembly assemblysModel = Assembly.LoadFrom(servicesDllFile);
                //if (!(File.Exists(servicesDllFile)))
                //{
                //    var msg = "EShop.Net.Model.dll 丢失，因项目解耦，需要先F6编译，再F5运行";
                //    throw new Exception(msg);
                //}
                //IEnumerable<Type> typelist = assemblysModel.GetTypes().Where(c => c.Namespace == "EShop.Net.Model.Entity");  // 获取此程序集中定义的类型
                //bool Backup = false;  // 是否备份
                //db.DbMaintenance.CreateDatabase();  // 创建一个数据库
                //if (Backup)
                //{
                //    db.CodeFirst.BackupTable().InitTables(typelist.ToArray());
                //}
                //else
                //{
                //    db.CodeFirst.InitTables(typelist.ToArray());
                //}
                #endregion

                #region 执行SQL 错误事件，可监控sql
                //db.Aop.OnLogExecuting = (sql, p) =>
                //{
                //    NLogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Other, "SqlSugar执行SQL错误事件打印Sql", sql);
                //};
                #endregion

                #region 执行SQL 错误事件
                //db.Aop.OnError = (exp) =>
                //{
                //    NLogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Other, "SqlSugar", "执行SQL错误事件", exp);
                //};
                #endregion
            });
        }
    }
}
